#!/usr/bin/env python 
#coding=utf-8
# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from jobs.models import Job
from jobs.models import Location
from django.utils import simplejson
import urllib
import re
import datetime
from django.http import Http404, HttpResponse
#==============================================
from django.utils import simplejson
from django.db import models
from django.core.serializers import serialize,deserialize
from django.db.models.query import QuerySet

class MyEncoder(simplejson.JSONEncoder):
    def default(self,obj):
            if isinstance(obj,QuerySet):
                return simplejson.loads(serialize('json',obj))
            if isinstance(obj,models.Model):
                return simplejson.loads(serialize('json',[obj])[1:-1])
            if hasattr(obj, 'isoformat'):
                return obj.isoformat()
            return simplejson.JSONEncoder.default(self,obj)

def jsonBack(json):
    if json[0] == '[':
        return deserialize('json',json)
    else:
        return deserialize('json','[' + json +']')

def getJson(result):
    return simplejson.dumps(result,cls=MyEncoder)

#def hello(request):
    #return HttpResponse("Hello World")

#======================星座=======================

def getHtml(url):
    page=urllib.urlopen(url)
    html=page.read()
    page.close()
    return html

def getResults(html,reg):
    astroList=re.compile(reg).findall(html)
    return astroList

def getAstro_name(html):
    regName = '<span>(.*?)<em>.*?</em></span>'
    return getResults(html,regName)

def getAstro_conts(html):
    regContent='<div class="lotconts">(.*?)</div>'
    return getResults(html,regContent)

def getAstro_spxz(html):
    regContent='<div class="tab"><h4>速配星座</h4><p>(.*?)</p></div>'
    return getResults(html,regContent)

def getAstro_zhys(html):
    regContent='<div class="tab"><h4>综合运势</h4><p>(.*?)</p></div>'
    return getResults(html,regContent)

def getAstro_str(html):
    #res = "星座:"
    res = getAstro_name(html)
    res += '<br/>今日运势 : '
    res += getAstro_conts(html)
    res += "<br/>速配星座 : "
    res += getAstro_spxz(html)
    res += "<br/>综合运势 : "
    res += getAstro_zhys(html)
    return res

def astro(request):
    html = getHtml('http://vip.astro.sina.com.cn/astro/view/taurus/day/')
    return HttpResponse(getAstro_str(html))

def astro_id(request, offset):
    if(offset>11):
        offset = int(offset) % 12
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    astro_arr = [
    "http://vip.astro.sina.com.cn/iframe/astro/view/aries/day/", #白羊座
    "http://vip.astro.sina.com.cn/iframe/astro/view/taurus/day/", #金牛座
    "http://vip.astro.sina.com.cn/iframe/astro/view/gemini/day/", #双子座
    "http://vip.astro.sina.com.cn/iframe/astro/view/cancer/day/", #巨蟹座
    "http://vip.astro.sina.com.cn/iframe/astro/view/leo/day/", #狮子座
    "http://vip.astro.sina.com.cn/iframe/astro/view/virgo/day/", #处女座
    "http://vip.astro.sina.com.cn/iframe/astro/view/libra/day/", #天秤座
    "http://vip.astro.sina.com.cn/iframe/astro/view/scorpio/day/", #天蝎座
    "http://vip.astro.sina.com.cn/iframe/astro/view/sagittarius/day/", #射手座
    "http://vip.astro.sina.com.cn/iframe/astro/view/capricorn/day/", #魔羯座
    "http://vip.astro.sina.com.cn/iframe/astro/view/aquarius/day/", #水瓶座
    "http://vip.astro.sina.com.cn/iframe/astro/view/pisces/day/", #双鱼座
    ]

    arr = astro_arr[offset]
    #html = "<html><body>%s it will be %s.</body></html>" % (offset,arr)
    html = getAstro_str(getHtml(arr))
    return HttpResponse(html)

#=======================json test============================

def index(request):
    object_list = Job.objects.order_by('-pub_date')[:10]
    t = loader.get_template('job_list.html')
    c = Context({
	'object_list':object_list,
    })
    return HttpResponse(t.render(c))

def get_host_json(request):
    json = {'name':'jiang'}
    return HttpResponse(simplejson.dumps(json, ensure_ascii=False))

def some_view(request):
    to_json = {
        "key1": "value1",
        "key2": "value2"
    }
    return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')

#====================json model===============================

from django.core import serializers
def jobs_list(request):
    #object_list = Location.objects.all()
    #jsonstr = json_encode(object_list)
    #raw = Location.objects.get(id=1)
    #print raw.toJson()
    
    #data = serializers.serialize("json", Location.objects.all())
    #print data
    jdata = getJson(Job.objects.all())
    print jdata
    #print jsonBack(jdata)
    #data = serializers.serialize('xml', Location.objects.all())
    #return HttpResponse(simplejson.dumps(jsonstr), mimetype='application/json')
    #return HttpResponse(simplejson.dumps(raw.toJson()), mimetype='application/json')
    #return HttpResponse(simplejson.dumps(data, ensure_ascii=False),mimetype='application/json')
    return HttpResponse(jdata)

#=======================datetime===============================

def current_datetime(request):
    now = datetime.datetime.now() 
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
    return HttpResponse(html)
